package org.kukker.upcoming;

import java.util.Properties;

import org.kukker.R;
import org.kukker.activity.BrowseSavedEventsActivity;
import org.kukker.activity.SearchEventsActivity;
import org.kukker.event.Event;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class UpcomingLocalService extends Service implements Runnable {

	public int num = 0;
	private final IBinder mBinder = new LocalBinder();
	private NotificationManager mNm;
	public volatile Looper mServiceLooper;
	public volatile ServiceHandler mServiceHandler;
	private Thread mThread1;
	private boolean isServiceDestroyed;
	private final int notification1_id = 1;

	public final class ServiceHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			/*
			 * Log.i("service2",this.getClass().getName() + " [ServiceHandler]
			 * handleMessage(), " + " what:"+msg.what );
			 */

			/*
			 * DISABLED FOR THIS MOMENT. NOT USING A SERVICE TO CALL A
			 * WEBSERVICE SINCE THE CALLING A SERVICE METHOD OPERATION IS
			 * SYNCHRONOUS. if(msg.what == 2){ UpcomingWebService uws = new
			 * UpcomingWebService(); uws.setParameters( (Properties) msg.obj);
			 * Event events [] = uws.get(); Log.i("service2","total results:
			 * "+events.length);
			 * 
			 * if(msg.callback != null){ msg.callback.run(); } }
			 */

			// Bundle arguments = (Bundle) msg.obj;

			// long endTime = System.currentTimeMillis() + 5*1000;
			// while(true){
			/*
			 * synchronized (this) { try { Log.i("UpcomingService",
			 * "(handler)thread sleeping..."); // wait(4*1000);
			 * Log.i("UpcomingService", "(handler)thread resume"); }
			 * 
			 * catch (Exception e) { } } ;
			 */
			// }
			// redispatch
			// dispatchMessage(msg);
			// Log.i("UpcomingService", "[ServiceHandler] Done");
			// stopSelf();
		}

		public void stop() {
			stopSelf();
		}

	};

	public class LocalBinder extends Binder {
		public UpcomingLocalService getService() {
			return UpcomingLocalService.this;
		}

		public void invokeWebService(UpcomingWebService uws) {
			// uws.get();

		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	public void onStart(int num, Bundle bundle) {
		// Log.i("service2",this.getClass().getName()+" , onStart");

		// waiting for the instantiation of handler that is happening on the
		// separate thread.
		while (mServiceHandler == null) {
			synchronized (this) {
				try {
					wait(100);
				} catch (InterruptedException e) {
				}
			}
		}

	}

	public void test() {
		while (mServiceHandler == null) {
			synchronized (this) {
				try {
					wait(100);
				} catch (InterruptedException e) {
				}
			}
		}

		Message mMsg = mServiceHandler.obtainMessage();
		mServiceHandler.dispatchMessage(mMsg);
	}

	@Override
	protected void onCreate() {
		mNm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		showNotification();
		isServiceDestroyed = false;
		
		//start this UpcomingLocalService runnable in a thread.
		new Thread(null, this, "KukkerLocalServiceThread").start();	
		
		/*
		mThread1 = new Thread(new Runnable() {
			@Override
			public void run() {
				while (!isServiceDestroyed) {
					try {					
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}					
				}
			}
		});
		*/
		
		// mThread1.start();

	}

	protected void onDestroy() {
		mServiceHandler.stop();
		mNm.cancel(this.notification1_id);
		isServiceDestroyed = true;
		// Tell the user we stopped.
		// Toast.makeText(this, "stopping service", Toast.LENGTH_SHORT).show();
	}

	private void showNotification() {
		// This is who should be launched if the user selects our notification.
		Intent contentIntent = new Intent(this, BrowseSavedEventsActivity.class);

		// This is who should be launched if the user selects the app icon in
		// the notification,
		// (in this case, we launch the same activity for both)
		Intent appIntent = new Intent(this, BrowseSavedEventsActivity.class);

		// In this sample, we'll use the same text for the ticker and the
		// expanded notification

		mNm.notify(this.notification1_id, // we use a string id because it is
											// a unique
				// number. we use it later to cancel the
				// notification
				new Notification(this, // our context
						R.drawable.kukkericon_16x16, // the icon for the
														// status
						// bar
						"Kukker2", // the text to display in the ticker
						System.currentTimeMillis(), // the timestamp for the
						// notification
						"Kukker2 service started", // the title for the
						// notification
						"background application process", // the details to
						// display in the
						// notification
						contentIntent, // the contentIntent (see above)
						R.drawable.kukkericon, // the app icon
						"Kukker2", // the name of the app
						appIntent));

	}

	@Override
	public void run() {
		while (true) {/*
						 * try { Thread.sleep(1000); } catch
						 * (InterruptedException e) { // TODO Auto-generated
						 * catch block e.printStackTrace(); }
						 * Log.i("UpcomingService","run()");
						 */

			Looper.prepare();

			mServiceLooper = Looper.myLooper();
			mServiceHandler = new ServiceHandler();

			Looper.loop();

		}

	}

}